package com.mic.nio.pool;

import com.mic.nio.NioServerBoss;
import com.mic.nio.NioServerWorker;

import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by yjq14 on 2018/2/10.
 */
public class NioSelectorRunnablePool {
    /**
     * boss 线程组
     */
    private final AtomicInteger bossIndex = new AtomicInteger();
    private Boss[] bosses;
    /**
     * worder线程组
     */
    private final AtomicInteger worderIndex = new AtomicInteger();
    private Worker[] workers;

    public NioSelectorRunnablePool(Executor boss, Executor worker) {
        initBoss(boss, 1);
        initWorker(worker, Runtime.getRuntime().availableProcessors() * 2);
    }

    /**
     *
      * @param boss boss 线程
     * @param count 线程数量
     */
    private void initBoss(Executor boss, int count) {
        this.bosses = new NioServerBoss[count];
        for (int i = 0; i < bosses.length; i++)
            bosses[i] = new NioServerBoss(boss, "boss" + i, this);
    }
    /**
     *
     * @param worker worker线程
     * @param count 线程数量
     */
    private void initWorker(Executor worker, int count) {
        this.workers = new NioServerWorker[count];
        for (int i = 0; i < workers.length; i++) {
            workers[i] = new NioServerWorker(worker, "worker" + i, this);
        }
    }

    public Worker nextWorker() {
        return workers[Math.abs(worderIndex.getAndIncrement() % workers.length)];
    }
    public Boss nextBoss() {
        return bosses[Math.abs(bossIndex.getAndIncrement() % bosses.length)];
    }
}
